package xjh.him.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import xjh.him.netty.Constant;

/**
 * 长度字段解码器
 * 根据长度字段对消息进行解码
 */
public class LengthFieldDecoder extends LengthFieldBasedFrameDecoder {
    public LengthFieldDecoder() {
        // 标记报文长度字段在报文的偏移量和长度
        super(Constant.MAX_FRAME_LENGTH, Constant.LENGTH_FIELD_OFFSET, Constant.LENGTH_FIELD_LENGTH);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        // 不是魔数开头的报文不接收
        if (in.getByte(in.readerIndex()) != Constant.MAGIC_NUM) {
            ctx.close();
            return null;
        }
        return super.decode(ctx, in);
    }
}
